<script setup name="SelectUser" lang="ts">
import { parseTime } from '../../../utils/ruoyi.ts'
import { authUserSelectAll, unallocatedUserList } from '@/api/system/role'
import type { UserQuery, UserVO } from '@/api/system/user/types'

type Key = string | number
const props = defineProps({
  roleId: {
    type: [Number, String],
  },
})
const emit = defineEmits(['ok'])
const message = useMessage()
const { proxy } = getCurrentInstance() as ComponentInternalInstance
const { sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_normal_disable'))

const userList = ref<UserVO[]>([])
const visible = ref(false)
const total = ref(0)
const userIds = ref<Array<string | number>>([])

const state = reactive<{
  selectedRowKeys: Key[]
  loading: boolean
}>({
  selectedRowKeys: [], // Check here to configure the default column
  loading: false,
})

const queryParams = reactive<UserQuery>({
  pageNum: 1,
  pageSize: 10,
  roleId: undefined,
  userName: undefined,
  phonenumber: undefined,
})

const tableRef = ref()
const queryFormRef = ref()

function show() {
  queryParams.roleId = props.roleId
  getList()
  visible.value = true
}

/** 查询数据 */
async function getList() {
  const res = await unallocatedUserList(queryParams)
  userList.value = res.rows
  total.value = res.total
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}
/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields()
  getList()
}

/** 选择授权用户操作 */
async function handleSelectUser() {
  const roleId = queryParams.roleId
  const ids = userIds.value.join(',')
  if (ids === '') {
    message.error('请选择要分配的用户')
    return
  }
  await authUserSelectAll({ roleId, userIds: ids })
  message.success('分配成功')
  emit('ok')
  visible.value = false
}

function customerRow(record: UserVO, index: number) {
  console.log(record, index)
  return {
    onClick: () => {
      state.selectedRowKeys.push(record.userId)
    },
  }
}

function onSelectChange(selectedRowKeys: Key[]) {
  state.selectedRowKeys = selectedRowKeys
}
// 暴露
defineExpose({
  show,
})
</script>

<template>
  <a-row>
    <a-modal v-model:open="visible" :mask-closable="false" :keyboard="false" title="选择用户" width="800px" top="5vh" append-to-body>
      <a-form ref="queryFormRef" :model="queryParams" layout="inline">
        <a-form-item label="用户名称" prop="userName">
          <a-input v-model:value="queryParams.userName" placeholder="请输入用户名称" clearable @keyup.enter="handleQuery" />
        </a-form-item>
        <a-form-item label="手机号码" prop="phonenumber">
          <a-input v-model:value="queryParams.phonenumber" placeholder="请输入手机号码" clearable @keyup.enter="handleQuery" />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" icon="Search" @click="handleQuery">
            搜索
          </a-button>
          <a-button icon="Refresh" @click="resetQuery">
            重置
          </a-button>
        </a-form-item>
      </a-form>
      <a-row class="mt-10px">
        <a-table ref="tableRef" row-key="userId" :row-selection="{ selectedRowKeys: state.selectedRowKeys, onChange: onSelectChange }" :custom-row="customerRow" :data-source="userList" height="260px">
          <a-table-column title="用户名称" data-index="userName" :ellipsis="true" />
          <a-table-column title="用户昵称" data-index="nickName" :ellipsis="true" />
          <a-table-column title="邮箱" data-index="email" :ellipsis="true" />
          <a-table-column title="手机" data-index="phonenumber" :ellipsis="true" />
          <a-table-column title="状态" align="center" prop="status">
            <template #default="{ record }">
              <dict-tag :options="sys_normal_disable" :value="record.status" />
            </template>
          </a-table-column>
          <a-table-column title="创建时间" align="center" prop="createTime" width="180">
            <template #default="{ record }">
              <span>{{ parseTime(record.createTime) }}</span>
            </template>
          </a-table-column>
        </a-table>
        <div class="text-right mt-5">
          <a-pagination
            v-show="total > 0"
            v-model:current="queryParams.pageNum" v-model:pageSize="queryParams.pageSize" :total="total"
            show-less-items @change="getList"
          />
        </div>
      </a-row>
      <template #footer>
        <div class="dialog-footer">
          <a-button type="primary" @click="handleSelectUser">
            确 定
          </a-button>
          <a-button @click="visible = false">
            取 消
          </a-button>
        </div>
      </template>
    </a-modal>
  </a-row>
</template>

<style scoped></style>
